<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="50%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="消息类别名称">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.templeId"
              placeholder="请输入消息类别"
              clearable
            />

            <span v-else>{{ formData.typeName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消息级别">
            <span>{{
              dictionaryStore.filterDictName(
                "MessageLevel",
                formData.messageLevel
              )
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="消息模式">
            <span>{{
              dictionaryStore.filterDictName(
                "MessageMode",
                formData.messageMode
              )
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="接收人条数">
            <span>{{
              Number(formData.reciveCount) + Number(formData.reciveErrCount)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="消息内容">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.content"
              placeholder="请输入消息内容"
              clearable
            />

            <span class="span-huanhang-detail" v-else>{{
              formData.content
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消息状态">
            <el-tag v-if="formData.messageStatus == '0'"> 发送中 </el-tag>
            <el-tag v-if="formData.messageStatus == '1'" type="success">
              发送成功
            </el-tag>
            <el-tag v-if="formData.messageStatus == '3'" type="warning">
              发送异常
            </el-tag>
            <el-tag v-if="formData.messageStatus == '2'" type="danger"
              >发送失败</el-tag
            >
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="发送时间">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.sendTime"
              placeholder="请输入发送时间"
              clearable
            />
            <span v-else>{{ formData.sendTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.errMessage">
          <el-form-item label="错误信息">
            <span>{{ formData.errMessage }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
      <el-card shadow="never" class="table-container">
        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            max-height="400"
            border
          >
            <el-table-column label="接收人" props="sendTime">
              <template #default="{ $index, row }">
                <span
                  >{{ row.recevieUserName }}{{ row.phone }}{{ row.email }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="消息状态">
              <template #default="scope">
                <el-tag v-if="scope.row.messageStatus == 1" type="success">
                  发送成功
                </el-tag>
                <el-tag v-if="scope.row.messageStatus == 2" type="danger"
                  >发送失败</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="发送时间" props="sendTime">
              <template #default="{ $index, row }">
                <span>{{ row.createTime }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SYSMESSAGESENDRECORDADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  templeId: [{ required: true, message: "请输入消息类别", trigger: "blur" }],
  organizationId: [
    { required: true, message: "请输入组织id", trigger: "blur" },
  ],
  recevieUserId: [
    { required: true, message: "请输入接收人用户id", trigger: "blur" },
  ],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  content: [{ required: true, message: "请输入消息内容", trigger: "blur" }],
  sendTime: [{ required: true, message: "请输入发送时间", trigger: "blur" }],
  createdUserId: [
    { required: true, message: "请输入创建人姓名 ID", trigger: "blur" },
  ],
  createdUserName: [
    { required: true, message: "请输入创建人姓名", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  templeId: "",
  title: "",
  firstName: "",
  messageLevel: "",
  messageMode: "",
  reciveCount: "",
  reciveErrCount: "",
  typeName: "",
  organizationId: "",
  recevieUserId: "",
  email: "",
  phone: "",
  content: "",
  messageStatus: "",
  sendTime: "",
  errMessage: "",
  createdUserId: "",
  createdUserName: "",
  details: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal?.id) {
      const {
        id,
        templeId,
        title,
        organizationId,
        recevieUserId,
        email,
        firstName,
        messageStatus,
        messageMode,
        reciveCount,
        reciveErrCount,
        messageLevel,
        typeName,
        phone,
        content,
        sendTime,
        errMessage,
        createdUserId,
        createdUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        templeId,
        title,
        organizationId,
        messageStatus,
        recevieUserId,
        messageMode,
        reciveCount,
        reciveErrCount,
        messageLevel,
        typeName,
        email,
        firstName,
        phone,
        content,
        sendTime,
        errMessage,
        createdUserId,
        createdUserName,
      });
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.templeId = "";
  formData.title = "";
  formData.organizationId = "";
  formData.recevieUserId = "";
  formData.email = "";
  formData.phone = "";
  formData.messageStatus = "";
  formData.typeName = "";
  formData.content = "";
  formData.firstName = "";
  formData.sendTime = "";
  formData.errMessage = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.messageMode = "";
  formData.reciveCount = "";
  formData.reciveErrCount = "";
  formData.messageLevel = "";
}

const loading = ref(false);

/** email消息发送记录保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/system/sysmessagesendrecord/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table");
    }
  });
}

/**消息发送记录查询详细表 */
async function getdetails() {
  const data = await request({
    url: "/system/sysmessagesendrecord/getDetails",
    method: "post",
    data: formData,
  });
  formData.details = data.data;
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
